#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <cstring>


using namespace std;
#define NUM 10

__thread int g_val = 0;

__thread pid_t pid = 0;
__thread unsigned long int tid = 0;

// C++中结构体类型创建实例不需要写struct，c++中类型与class类似
struct Thread_Data
{
    string name;
};

void Thread_Inin(Thread_Data *td, int number)
{
    td->name = "thraed-" + to_string(number);
}

string toHex(pthread_t td)
{
    char buffer[1024];
    snprintf(buffer, sizeof(buffer), "0x%lx", td);
    return buffer;
}

void *Thread_Routine(void *arg)
{
    Thread_Data *td = static_cast<Thread_Data *>(arg);
    int i = 0;
    tid = pthread_self();
    pid = getpid();
    pthread_detach(tid);
    while (i < 10)
    {
        cout << "pid: " << pid << ",tid: " << toHex(tid) << ", threadname: " << td->name << ' '
             << "g_val: " << g_val << " &g_val: " << &g_val << endl;
        sleep(1);
        i++, g_val++;
    }
    delete td;
    return nullptr;
}

int main()
{
    vector<pthread_t> tds;

    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid;
        Thread_Data *td = new Thread_Data;
        Thread_Inin(td, i);

        pthread_create(&tid, nullptr, Thread_Routine, td);
        tds.push_back(tid);
        sleep(1);
    }
    sleep(1); // 很关键，需要保证线程们都已经分离了

    int n=0;
    for (int i = 0; i < NUM; i++)
    {
        if ((n=pthread_join(tds[i], nullptr)) == 0)
            cout << "pthread wait success" << endl;
        else
            cout << "pthread wait failed" <<" n= " <<n <<" "<<strerror(n)<< endl;
    }
    return 0;
}
